﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;

namespace MvcTemplates
{
    public abstract class TagBuilderAttribute : HtmlAttributesAttribute
    {
        public Type TagBuilderType { get; set; }

        private TagBuilder _tag;
        protected TagBuilder Tag
        {
            get
            {
                if ( _tag == null )
                {
                    _tag = CreateTagBuilder();
                }
                return _tag;
            }
        }
        
        protected TagBuilder CreateTagBuilder()
        {
            return ( TagBuilder )Activator.CreateInstance( TagBuilderType );
        }

        protected MvcHtmlString GetStartTagAndInnerContent()
        {
            var output = new StringBuilder();
            output.Append( Tag.ToString( TagRenderMode.StartTag ) );
            output.Append( Tag.InnerHtml );
            return MvcHtmlString.Create( output.ToString() );
        }

        public virtual MvcHtmlString GetStartTagAndInnerContent( HtmlHelper helper, string propertyName )
        {
            ModelMetadata mmd;
            
            if ( string.IsNullOrEmpty( propertyName ) )
            {
                mmd = helper.ViewData.ModelMetadata;
            }
            else
            {
                mmd = ModelMetadata.FromStringExpression( propertyName, helper.ViewData );
            }

            Tag.MergeAttributes( mmd.MergeAttributes( null, GetType() ) );
            return GetStartTagAndInnerContent();
        }

        public virtual MvcHtmlString GetEndTag( HtmlHelper helper )
        {
            return MvcHtmlString.Create( Tag.ToString( TagRenderMode.EndTag ) );
        }
    }
}
